import os

import requests

from service.base_service.logger_service import logger
from service.base_service.task_service import TaskService
from service.extract_service.data_query_service import DataQueryService
from service.transform_service.csv_service import CsvService
from service.base_service.table_service import TableService


class ProcessService:
    def process_task_with_params(self, dispatch_code, task_id, dynamic_params):
        # task_id 是固定参数
        # dynamic_params 是动态参数字典
        # 通过id获取自定义task
        task = TaskService().get_task_by_task_id(dispatch_code, task_id)

        # 拿到参数进行判断，如果调用时没传参数则使用模板的默认参数/函数
        data_query_service = DataQueryService()
        if dynamic_params is None or dynamic_params == {} or dynamic_params == '{}' or dynamic_params == 'null':
            execute_sql = data_query_service.construct_sql(task.sql.sql_template, task.sql.sql_variable)
        else:
            execute_sql = data_query_service.construct_sql(task.execute_content, dynamic_params)
        logger.info(f"执行sql: {execute_sql}")

        # 通过查询库和自定义sql拿到查询结果数据
        data = data_query_service.execute_query(task.execute_database, execute_sql)

        # 将查询结果转为csv文件
        csv_service = CsvService()
        csv_path = csv_service.generate_csv_file(data)

        # 判断接收数据的地址是否为本机
        if task.ser == 'localhost' or task.send_address_host == '127.0.0.1':
            # 本机发送
            # 直接从生成csv文件的路径读取数据并加载到表中
            result = csv_service.load_data_from_csv(csv_path, task.storage_database, task.storage_table)
        else:
            # 远程发送
            # 发送csv文件到指定地址
            files = {
                'file': (os.path.basename(csv_path), open(csv_path, 'rb')),
            }

            # 发送 POST 请求
            result = requests.post(task.receive_service, files=files)

            # 输出响应结果
            logger.info(f"{csv_path}文件已发送至{task.send_address_url},响应信息为{result}")

        return result
